//
//  EncryptPlugin.swift
//  CooperSwift
//
//  Created by Mac on 2019/12/25.
//  Copyright © 2019 CooperSwift. All rights reserved.
//

import Foundation
import Moya
import SwiftyJSON
import CryptoSwift
import RxSwift

struct EncryptPlugin: PluginType {
    
    /// Called to modify a request before sending.
    func prepare(_ request: URLRequest, target: TargetType) -> URLRequest { 
        return request
    }
    
    /// Called immediately before a request is sent over the network (or stubbed).
    func willSend(_ request: RequestType, target: TargetType) {
        
    }
    
    /// Called after a response has been received, but before the MoyaProvider has invoked its completion handler.
    func didReceive(_ result: Result<Moya.Response, MoyaError>, target: TargetType) {
        
    }
    
    /// Called to modify a result before completion.
    func process(_ result: Result<Moya.Response, MoyaError>, target: TargetType) -> Result<Moya.Response, MoyaError> {
        if case let .success(response) = result {
            // 判断数据解密
            guard let data = try? response.mapString(), let resultModel = ResultModel.deserialize(from: data), let aes = try? AES(key: Padding.zeroPadding.add(to: "dcxj_hd".bytes, blockSize: AES.blockSize), blockMode: ECB(), padding: .pkcs7) else {
                return result
            }
            // 解密判断数据
            if (resultModel.success ?? false) && resultModel.data != nil {
                let bytes = Data(hex: (resultModel.data as! String)).bytes
                guard let decryptRes = try? aes.decrypt(bytes) else { return result }
                let response = Moya.Response.init(statusCode: 200, data: Data(decryptRes))
                return Result.success(response)
            }
            
//            if case let res = JSON(data), res["success"] == true {
//                let aes = try? AES(key: Padding.zeroPadding.add(to: "dcxj_hd".bytes, blockSize: AES.blockSize), blockMode: ECB(), padding: .pkcs7)
//                guard let decryptRes = try? aes?.decrypt(Data(hex: res["data"].stringValue).bytes) else { return result }
//                let response = Moya.Response.init(statusCode: 200, data: Data(decryptRes!))
////                if let resultRes = String(bytes: decryptRes!, encoding: .utf8) {
////                    log.debug("解密结果-->" + resultRes)
////                }
//                return Result.success(response)
//            }
        }
        return result
    }
    
}
